package com.mercenary.wein.screenControl.dao;

import com.mercenary.wein.screenControl.bean.CommandBean;
import com.mercenary.wein.screenControl.bean.CommandDetailBean;
import com.mercenary.wein.screenControl.bean.ScheduleTask;
import com.mercenary.wein.screenControl.ui.util.Constants;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.sql.Connection;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by tuxiao on 2017/3/19.
 */
public class CommandDao {
    Log log = LogFactory.getLog(CommandDao.class);

    public List<CommandDetailBean> getCommandList(){
        String sql = "select p.id,t.dname as dName,p.submit_time,q.actionName,p.content, " +
                "case p.status when 0 then '执行中' " +
                "when 1 then '执行成功' " +
                "when 2 then '执行失败' end as status "  +
                "from tasks p join device t on t.serialNo=p.did join commandmeta q on p.cid=q.actionId " +
                "order by p.id asc limit 100";
        log.info("getCommandList");
        Connection connection = ConnectDb.Connect();
        QueryRunner queryRunner = new QueryRunner();
        try {
            List<CommandDetailBean> results = queryRunner.query(connection,sql,
                    new BeanListHandler<CommandDetailBean>(CommandDetailBean.class));
            DbUtils.close(connection);
            if(results.size()==0)return null;
            return results;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查看设备是否有正在运行的任务
     * @param did
     * @return long[id,submitime]
     */
    public long[] isRunning(String did){
        String sql  = "select * from tasks where did =? and status=0";
        log.info("check status");
        Connection connection = ConnectDb.Connect();
        QueryRunner queryRunner = new QueryRunner();
        try {
            List<CommandDetailBean> results = queryRunner.query(connection,sql,
                    new BeanListHandler<CommandDetailBean>(CommandDetailBean.class),did);
            DbUtils.close(connection);
            if(results.size()!=0)return new long[]{results.get(0).getId(), new SimpleDateFormat("yyyyMMdd HH:mm:ss").parse(results.get(0).getSubmit_time()).getTime()}  ;
            return new long[]{0l,0l};
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return new long[]{0l,0l};
    }

    public void shutdownTask(long id){
        String sql = "update tasks set status=2 where id=?";
        log.info("shutdownTask:"+id);
        Connection connection = ConnectDb.Connect();
        QueryRunner queryRunner = new QueryRunner();
        try {
            queryRunner.update(connection,sql,id);
            DbUtils.close(connection);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void updateTask(long id,int status){
        String sql = "update tasks set status=? where id=?";
        log.info("update task:id->"+id+" | status->"+status);
        Connection connection = ConnectDb.Connect();
        QueryRunner queryRunner = new QueryRunner();
        try {
            queryRunner.update(connection,sql,status,id);
            DbUtils.close(connection);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public long insertTask(CommandBean commandBean){
        String did = commandBean.getSerialNo();
        int actionId = commandBean.getActionId();
        String content = commandBean.getContent();
        String submit_time = commandBean.getSubmitTime();
        String sql = "insert into tasks values(null,?,?,0,?,?,?)";
        log.info("insertTask : deviceId->"+did+" | content->"+content+" | action->"+ Constants.actionMap.get(actionId));

        Connection connection = ConnectDb.Connect();
        QueryRunner queryRunner = new QueryRunner();
        try {
            long id = queryRunner.insert(connection,sql,new ScalarHandler<Long>(),actionId,content,submit_time,did,commandBean.getExeModeBean().toJson());
            DbUtils.close(connection);
            return id;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public long insertScheduleTask(CommandBean commandBean){
        String sql = "insert into scheduletask values(null,?,?,?)";
        Connection connection = ConnectDb.Connect();
        QueryRunner queryRunner = new QueryRunner();
        try {
            long id = queryRunner.insert(connection,sql,new ScalarHandler<Long>(),commandBean.toJson(),commandBean.getExeModeBean().getJobName(),commandBean.getZid());
            DbUtils.close(connection);
            return id;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public List<ScheduleTask> getScheduleTask(){
        String sql = "select * from scheduleTask";
        log.info("getScheduleTasks");
        Connection connection = ConnectDb.Connect();
        QueryRunner queryRunner = new QueryRunner();
        try {
            List<ScheduleTask> results = queryRunner.query(connection,sql,
                    new BeanListHandler<ScheduleTask>(ScheduleTask.class));
            DbUtils.close(connection);
            if(results.size()==0)return null;
            return results;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<ScheduleTask> getScheduleTaskByZid(long zid){
        String sql = "select * from scheduleTask where zid=?";
        log.info("getScheduleTasks");
        Connection connection = ConnectDb.Connect();
        QueryRunner queryRunner = new QueryRunner();
        try {
            List<ScheduleTask> results = queryRunner.query(connection,sql,
                    new BeanListHandler<ScheduleTask>(ScheduleTask.class),zid);
            DbUtils.close(connection);
            return results;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return new ArrayList<ScheduleTask>();
    }

    public void deleteSchedualTask(long id){
        String sql = "delete from scheduletask where id=?";
        Connection connection = ConnectDb.Connect();
        QueryRunner queryRunner = new QueryRunner();
        try {
            queryRunner.update(connection,sql,id);
            DbUtils.close(connection);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public List<ScheduleTask> getSchdualJobs(){
        String sql="select jobName,zid from scheduletask group by jobName,zid";
        log.info("getSchdualJobs");
        Connection connection = ConnectDb.Connect();
        QueryRunner queryRunner = new QueryRunner();
        try {
            List<ScheduleTask> results = queryRunner.query(connection,sql,
                    new BeanListHandler<ScheduleTask>(ScheduleTask.class));
            DbUtils.close(connection);
            return results;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return new ArrayList<ScheduleTask>();
    }

    public void removeJob(long zid){
        String sql = "delete from scheduletask where zid=?";
        Connection connection = ConnectDb.Connect();
        QueryRunner queryRunner = new QueryRunner();
        try {
            queryRunner.update(connection,sql,zid);
            DbUtils.close(connection);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
